package com.neusoft.neuiotms.dcvm.service.impl;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.bizcore.webauth.secret.AuditOplogService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AuditOplogServiceImpl implements AuditOplogService {
    @Value("${casp.nginxIndexUrl:''}")
    private String nginxIndexUrl;
    @PersistenceContext
    private EntityManager entityManager;

    private final static String sql =
            "INSERT INTO AUDIT_OPLOG ( LogTime, SubUser, App, Dip, Sip, AppModule, OpType, OpText) VALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";

    @Transactional
    @Override
    public void create(String subUser, String sip, String appModule, String opType, String opText) {

        if (AuditOplogServiceImpl.log.isDebugEnabled()) {
            AuditOplogServiceImpl.log.debug("save audit log, {},{},{},{},{}", subUser, sip, appModule, opType,
                    opText);
        }

        final String createSql = String.format(AuditOplogServiceImpl.sql,
                DateFormatUtils.format(new Date(), DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.getPattern()),
                subUser, "IDCKSH-DCVM-NEU", this.nginxIndexUrl.substring(7).replace("/", ""), sip, appModule, opType,
                opText);

        this.entityManager.createNativeQuery(createSql).executeUpdate();
    }

}
